package cn.scw.common.utils;

import cn.scw.common.exception.CustomException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.security.SecureRandom;
import java.util.Random;

/**
 * @description:
 * @author: lj
 * @create: 2020-06-11
 **/
public class SMSUtils {
    public final static String KEY ="LTAI4GHAW3gKonVrLrzYBD8z";
    public final static String SECRET ="UCyawfnbTRZQ9Q8fQQ7t1YHmNnP4Tg";
    public final static String REGION ="cn-hangzhou";
    public final static String SIGN_NAME ="橘子味的猫";
    public final static String TEMPLATE_CODE ="SMS_128645563";


//    public static void main(String[] args) {
//        send("18510364392","lj");
//    }

    public static void send(String phoneNumber,String code){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", KEY, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", REGION);
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", SIGN_NAME);
        request.putQueryParameter("TemplateCode", TEMPLATE_CODE);
        JSONObject json=new JSONObject();
        json.put("code",code);
        request.putQueryParameter("TemplateParam", json.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String res=response.getData();
            JSONObject js= JSON.parseObject(res);
            if (!"OK".equals(js.getString("Code")))
                throw new CustomException("验证码发送失败");
        } catch (ClientException e) {
            e.printStackTrace();
            throw new CustomException("验证码发送失败");
        }
    }

    private static final Random RANDOM = new SecureRandom();
    private static final String SYMBOLS = "0123456789";

    public static String getNonce_str() {

        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[4];

        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }

        return new String(nonceChars);
    }

}
